package com.ccsoft.zknote.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailUtil;
import com.ccsoft.zknote.pojo.system.BusinessException;
import com.ccsoft.zknote.service.IMailService;
import com.ccsoft.zknote.service.IUserService;
import com.ccsoft.zknote.util.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author chanchaw
 * @create 2023-07-11 12:51
 */
@Service
public class MailServiceImpl implements IMailService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;

    /**
     * 发送给用户邮箱验证码
     * @param userEmail
     * @return
     */
    @Override
    public String getVerificationCode(String userEmail) {
        // 1. 检测邮件不可重复注册
        if(userService.isExists8Email(userEmail)) throw new BusinessException("该邮箱已经使用，不可重复注册！");

        // 2. 发送验证码到目标邮箱
        String vc = RandomUtil.randomString(6);// 获取6个字符的数字+英文验证码
        String emailContent = "<p>【天尘 note】尊敬的" + userEmail + ":</p>"
                + "<p>您正在通过邮箱注册账号，请勿泄露验证码！</p>"
                + "<p>验证码：<b style='font-size: 20px;color: blue;'>" + vc + "</b></p>"
                + "<p>有效时间为" + SystemUtils.VERIFICATION_CODE_DURATION + "分钟</p>";

        try {
            MailUtil.send(userEmail,"天尘 note 注册验证码",emailContent, true);
        } catch (Exception e) {
            throw new BusinessException("发送注册验证码邮件时出现异常！");
        }

        // 将验证码保存到 redis 15分钟，eravc = email register account varification code
        // = 使用邮箱注册账号的验证码
        String eravcTokenKey = "eravcToken:" + userEmail + ":" + SystemUtils.getUUID();
        try {
            redisTemplate.opsForValue().set(eravcTokenKey, vc, SystemUtils.VERIFICATION_CODE_DURATION, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new BusinessException("验证码存储失败！");
        }
        return eravcTokenKey;
    }
}
